﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WanMeiCommon;
using WanMeiModel;
using WanMeiSqlTools;

namespace WanMeiBussinessService
{
    public class HeroService : IHeroService
    {

        #region IHeroService 成员
        /// <summary>
        /// 获取角色选择界面，所有英雄对应的当前玩家的相关信息
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public List<ChoseHeroItem> GetHerosByUserName(string userName)
        {
            var result = new List<ChoseHeroItem>();
            SqlParameter[] parms = 
            {
                new SqlParameter("@UserName",userName)
            };
            string sql = "select HeroName,Introduce,ch.Id as HeroId,cr.RoleNick,ISNULL(cr.GameLevel,1) as GameLevel from C_Hero ch left join C_Role cr on cr.HeroId = ch.Id and cr.UserName= @UserName  where PublicStatus=1";
            try
            {
                var dt = new SqlManager().ExecuteDataset(CommandType.Text, sql, parms);
                if (dt != null && dt.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
                    {
                        result.Add(new ChoseHeroItem()
                        {
                            HeroId = Convert.ToInt32(dt.Tables[0].Rows[i]["HeroId"]),
                            HeroIntroduce = dt.Tables[0].Rows[i]["Introduce"].ToString(),
                            HeroName = dt.Tables[0].Rows[i]["HeroName"].ToString(),
                            RoleNick = dt.Tables[0].Rows[i]["RoleNick"].ToString(),
                            IsHasNick = string.IsNullOrEmpty(dt.Tables[0].Rows[i]["RoleNick"].ToString()) ? 0 : 1,
                            GameLevel = Convert.ToInt32(dt.Tables[0].Rows[i]["GameLevel"]),
                            GameLevelTitle = ToolManager.GetGameLevelTitle(dt.Tables[0].Rows[i]["HeroName"].ToString(), Convert.ToInt32(dt.Tables[0].Rows[i]["GameLevel"]))
                        });
                    }

                }
            }
            catch (Exception ex)
            {
                LogManger.Instance.WriteLog(" 获取角色选择界面，所有英雄对应的当前玩家的相关信息错误:" + ex.ToString());

            }

            return result;
        }

        /// <summary>
        /// 获取当前角色装备上的装备信息列表
        /// </summary>
        /// <param name="un"></param>
        /// <param name="heroid"></param>
        /// <returns></returns>
        public List<HeroEquipmentItem> GetCurrentEquipments(string un, int heroid)
        {
            var result = new List<HeroEquipmentItem>();
            SqlParameter[] parms = 
            {
                new SqlParameter("@un",SecretClass.DecryptQueryString(un)),
                new SqlParameter("@heroid",heroid),
            };
            string sql = "select cb.Id,ce.SalePrice,EquipmentLevel,ce.Place,EquipmentName,Introduce,InitArmor,InitCriticalValue,InitHealthPoint,InitMagicPower,NeedGameLevel,ImgPath,ApValue,[Power],Quality,NeedRole,ce.Money from C_BackPack cb join C_Equipment ce on cb.PropId = ce.Id where cb.UserName =@un and IsUseing = 1 and cb.PublicStatus=1 and cb.HeroId=@heroid";


            var dt = new SqlManager().ExecuteDataset(CommandType.Text, sql, parms);
            if (dt != null && dt.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
                {
                    var tempEquipmentLevel = Convert.ToInt32(dt.Tables[0].Rows[i]["EquipmentLevel"]);//如果是装备，强化等级。。目前暂时的计算逻辑，本身的属性增益+本身增益*0.2*强化等级
                    var tempApValue = Convert.ToInt32(dt.Tables[0].Rows[i]["ApValue"]);
                    var tempInitArmor = Convert.ToInt32(dt.Tables[0].Rows[i]["InitArmor"]);
                    var tempInitCriticalValue = Convert.ToInt32(dt.Tables[0].Rows[i]["InitCriticalValue"]);
                    var tempInitHealthPoint = Convert.ToInt32(dt.Tables[0].Rows[i]["InitHealthPoint"]);
                    var tempInitMagicPower = Convert.ToInt32(dt.Tables[0].Rows[i]["InitMagicPower"]);
                    result.Add(new HeroEquipmentItem()
                    {

                        Id = Convert.ToInt32(dt.Tables[0].Rows[i]["Id"]),
                        SalePrice = Convert.ToInt32(dt.Tables[0].Rows[i]["SalePrice"]),
                        EquipmentLevel = Convert.ToInt32(dt.Tables[0].Rows[i]["EquipmentLevel"]),
                        Place = Convert.ToInt32(dt.Tables[0].Rows[i]["Place"]),
                        EquipmentName = dt.Tables[0].Rows[i]["EquipmentName"].ToString(),
                        Introduce = dt.Tables[0].Rows[i]["Introduce"].ToString(),
                        ApValue = GetEquiValue(tempApValue, tempEquipmentLevel),
                        InitArmor = GetEquiValue(tempInitArmor, tempEquipmentLevel),
                        InitCriticalValue = GetEquiValue(tempInitCriticalValue, tempEquipmentLevel),
                        InitHealthPoint = GetEquiValue(tempInitHealthPoint, tempEquipmentLevel),
                        InitMagicPower = GetEquiValue(tempInitMagicPower, tempEquipmentLevel),
                        NeedGameLevel = Convert.ToInt32(dt.Tables[0].Rows[i]["NeedGameLevel"]),
                        ImgPath = string.Format("{0}{1}/{2}", ConfigSettings.Instance.GameProImgHost, PropUpload.Instance.FolderName, dt.Tables[0].Rows[i]["ImgPath"].ToString()),
                        Quality = Convert.ToInt32(dt.Tables[0].Rows[i]["Quality"]),
                        NeedRole = Convert.ToInt32(dt.Tables[0].Rows[i]["NeedRole"]),
                        Money = Convert.ToInt32(dt.Tables[0].Rows[i]["Money"])
                    });
                }

            }

            return result;
        }

        /// <summary>
        /// 获取当前角色背包道具信息
        /// </summary>
        /// <param name="un"></param>
        /// <param name="heroid"></param>
        /// <returns></returns>
        public HeroBackPackPropManager GetCurrentBackPackInfos(string un, int heroid)
        {
            var result = new HeroBackPackPropManager();
            SqlParameter[] parms = 
            {
                new SqlParameter("@un",un),
                new SqlParameter("@heroId",heroid),
            };
            var dt = new SqlManager().ExecuteDataset(CommandType.StoredProcedure, "wanmei_proc_getbackpackprops", parms);
            //装备集合
            if (dt != null && dt.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < dt.Tables[0].Rows.Count; i++)
                {
                    var tempEquipmentLevel = Convert.ToInt32(dt.Tables[0].Rows[i]["EquipmentLevel"]);//如果是装备，强化等级。。目前暂时的计算逻辑，本身的属性增益+本身增益*0.2*强化等级
                    var tempApValue = Convert.ToInt32(dt.Tables[0].Rows[i]["ApValue"]);
                    var tempInitArmor = Convert.ToInt32(dt.Tables[0].Rows[i]["InitArmor"]);
                    var tempInitCriticalValue = Convert.ToInt32(dt.Tables[0].Rows[i]["InitCriticalValue"]);
                    var tempInitHealthPoint = Convert.ToInt32(dt.Tables[0].Rows[i]["InitHealthPoint"]);
                    var tempInitMagicPower = Convert.ToInt32(dt.Tables[0].Rows[i]["InitMagicPower"]);

                    result.Equipments.Add(new HeroEquipmentItem()
                    {

                        Id = Convert.ToInt32(dt.Tables[0].Rows[i]["Id"]),
                        PropType = Convert.ToInt32(dt.Tables[0].Rows[i]["PropType"]),
                        PropId = Convert.ToInt32(dt.Tables[0].Rows[i]["PropId"]),
                        SalePrice = Convert.ToInt32(dt.Tables[0].Rows[i]["SalePrice"]),
                        EquipmentLevel = Convert.ToInt32(dt.Tables[0].Rows[i]["EquipmentLevel"]),
                        Place = Convert.ToInt32(dt.Tables[0].Rows[i]["Place"]),
                        EquipmentName = dt.Tables[0].Rows[i]["EquipmentName"].ToString(),
                        Introduce = dt.Tables[0].Rows[i]["Introduce"].ToString(),
                        ApValue = GetEquiValue(tempApValue, tempEquipmentLevel),
                        InitArmor = GetEquiValue(tempInitArmor, tempEquipmentLevel),
                        InitCriticalValue = GetEquiValue(tempInitCriticalValue, tempEquipmentLevel),
                        InitHealthPoint = GetEquiValue(tempInitHealthPoint, tempEquipmentLevel),
                        InitMagicPower = GetEquiValue(tempInitMagicPower, tempEquipmentLevel),
                        NeedGameLevel = Convert.ToInt32(dt.Tables[0].Rows[i]["NeedGameLevel"]),
                        ImgPath = string.Format("{0}{1}/{2}", ConfigSettings.Instance.GameProImgHost, PropUpload.Instance.FolderName, dt.Tables[0].Rows[i]["ImgPath"].ToString()),
                        Quality = Convert.ToInt32(dt.Tables[0].Rows[i]["Quality"]),
                        NeedRole = Convert.ToInt32(dt.Tables[0].Rows[i]["NeedRole"]),
                        Money = Convert.ToInt32(dt.Tables[0].Rows[i]["Money"])
                    });
                }

            }

            //材料集合
            if (dt != null && dt.Tables[1].Rows.Count > 0)
            {
                for (int i = 0; i < dt.Tables[1].Rows.Count; i++)
                {
                    result.Materials.Add(new HeroMaterialItem()
                    {
                        Id = Convert.ToInt32(dt.Tables[1].Rows[i]["Id"]),
                        PropType = Convert.ToInt32(dt.Tables[1].Rows[i]["PropType"]),
                        PropId = Convert.ToInt32(dt.Tables[1].Rows[i]["PropId"]),
                        MaterialName = dt.Tables[1].Rows[i]["MaterialName"].ToString(),
                        Introduce = dt.Tables[1].Rows[i]["Introduce"].ToString(),
                        Num = Convert.ToInt32(dt.Tables[1].Rows[i]["Num"]),
                        ImgPath = string.Format("{0}{1}/{2}", ConfigSettings.Instance.GameProImgHost, PropUpload.Instance.FolderName, dt.Tables[1].Rows[i]["ImgPath"].ToString()),
                        Money = Convert.ToInt32(dt.Tables[0].Rows[i]["Money"])

                    });
                }
            }
            //宝石集合
            if (dt != null && dt.Tables[2].Rows.Count > 0)
            {
                for (int i = 0; i < dt.Tables[2].Rows.Count; i++)
                {
                    result.Gemstones.Add(new HeroGemstoneItem()
                    {
                        Id = Convert.ToInt32(dt.Tables[2].Rows[i]["Id"]),
                        PropType = Convert.ToInt32(dt.Tables[2].Rows[i]["PropType"]),
                        PropId = Convert.ToInt32(dt.Tables[2].Rows[i]["PropId"]),
                        GemstoneName = dt.Tables[2].Rows[i]["GemstoneName"].ToString(),
                        Introduce = dt.Tables[2].Rows[i]["Introduce"].ToString(),
                        Num = Convert.ToInt32(dt.Tables[2].Rows[i]["Num"]),
                        ImgPath = string.Format("{0}{1}/{2}", ConfigSettings.Instance.GameProImgHost, PropUpload.Instance.FolderName, dt.Tables[2].Rows[i]["ImgPath"].ToString()),
                        Money = Convert.ToInt32(dt.Tables[0].Rows[i]["Money"])

                    });
                }
            }

            return result;
        }

        private int GetEquiValue(int val, int level)
        {
            int result = 0;
            if (val == 0)
            {
                return result;
            }
            else
            {
                if (level == 0)
                {
                    return val;
                }
                //乘以系数后，是小于1的小数按1算，
                var xs = val * 0.2;
                if (xs > 0 && xs < 1)
                {
                    xs = 1.0;
                }
                result = val + Convert.ToInt32(xs) * level;
            }
            return result;
        }
        /// <summary>
        /// 将背包装备脱下
        /// </summary>
        /// <param name="un"></param>
        /// <param name="backId"></param>
        /// <returns></returns>
        public bool TakeOff(string un, int backId)
        {
            var result = false;
            var sql = "update C_BackPack set IsUseing = 0 WHERE Id= @Id and UserName=@un";
            SqlParameter[] parms = 
            {
                new SqlParameter("@un",un),
                new SqlParameter("@Id",backId),
            };
            try
            {
                var obj = new SqlManager().ExecuteNonQuery(CommandType.Text, sql, parms);
                if (obj != null)
                {
                    if (Convert.ToInt32(obj) == 1)
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {

                LogManger.Instance.WriteLog("将背包装备脱下错误:" + ex.ToString());
            }
            return result;
        }

        /// <summary>
        /// 背包的装备，装备上
        /// </summary>
        /// <param name="un"></param>
        /// <param name="backId"></param>
        /// <param name="heroId"></param>
        /// <returns></returns>
        public int TakeOn(string un, int backId, int heroId)
        {
            var sqlManager = new SqlManager();
            SqlParameter rtn_err = sqlManager.GetRtnParameter();
            SqlParameter[] parms = 
            {
                new SqlParameter("@backId",backId),
                new SqlParameter("@un",un),
                new SqlParameter("@heroId",heroId),
                rtn_err
            };
            sqlManager.ExecuteNonQuery(CommandType.StoredProcedure, "wanmei_pro_takeon", parms);
            if (rtn_err.Value != null)
            {
                LogManger.Instance.WriteLog("背包的装备，装备上wanmei_pro_takeon返回:" + rtn_err.Value);
                return int.Parse(rtn_err.Value.ToString());
            }
            return -1;
        }


        /// <summary>
        /// 获取当前账户的当前选择的角色信息
        /// </summary>
        /// <param name="un"></param>
        /// <param name="heroId"></param>
        /// <returns></returns>
        public UserInfoModelResult GetUserInfoModel(string un, int heroId)
        {
            UserRoleModel userRole = new UserRoleModel();
            UserRoleBaseAttributeItem userBaseInfo = new UserRoleBaseAttributeItem();
            SqlParameter[] parms = 
            { 
                new SqlParameter("@un",SecretClass.DecryptQueryString(un)),
                new SqlParameter("@heroId",heroId)
            };
            string sql = "select * from C_Role where HeroId=@heroId and UserName=@un";
            var ds = new SqlManager().ExecuteDataset(CommandType.Text, sql, parms);
            string heroName = ds.Tables[0].Rows[0]["HeroId"].ToString() == "1" ? "剑士" : "魔法师";
            if (ds != null && ds.Tables[0].Rows.Count == 1)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                userRole.Armor = Convert.ToInt32(dr["Armor"]);
                userRole.UserName = un;
                userRole.CriticalValue = Convert.ToInt32(dr["CriticalValue"]);
                userRole.DepositValue = Convert.ToInt32(dr["DepositValue"]);
                userRole.ExValue = long.Parse(dr["ExValue"].ToString());
                userRole.GameLevel = Convert.ToInt32(dr["GameLevel"]);
                userRole.HealthPoint = Convert.ToInt32(dr["HealthPoint"]);
                userRole.HeroId = Convert.ToInt32(dr["HeroId"]);
                userRole.Id = Convert.ToInt32(dr["Id"]);
                userRole.MagicPower = Convert.ToInt32(dr["MagicPower"]);
                userRole.PotentialValue = long.Parse(dr["PotentialValue"].ToString());
                userRole.RoleNick = dr["RoleNick"].ToString();
                userRole.VipLevel = Convert.ToInt32(dr["VipLevel"]);
                userRole.Money = long.Parse(dr["Money"].ToString());
                userRole.ApValue = Convert.ToInt32(dr["ApValue"]);
                userRole.LevelTitle = ToolManager.GetGameLevelTitle(heroName, Convert.ToInt32(dr["GameLevel"]));
                userBaseInfo.Armor = Convert.ToInt32(dr["Armor"]);
                userBaseInfo.CriticalValue = Convert.ToInt32(dr["CriticalValue"]);
                userBaseInfo.ExValue = long.Parse(dr["ExValue"].ToString());
                userBaseInfo.GameLevel = Convert.ToInt32(dr["GameLevel"]);
                userBaseInfo.HealthPoint = Convert.ToInt32(dr["HealthPoint"]);
                userBaseInfo.HeroId = Convert.ToInt32(dr["HeroId"]);
                userBaseInfo.MagicPower = Convert.ToInt32(dr["MagicPower"]);
                userBaseInfo.PotentialValue = long.Parse(dr["PotentialValue"].ToString());
                userBaseInfo.Money = long.Parse(dr["Money"].ToString());
                userBaseInfo.ApValue = Convert.ToInt32(dr["ApValue"]);

            }
            //获取当前装备信息
            List<HeroEquipmentItem> eqList = GetCurrentEquipments(un, heroId);
            ////角色AP，血，蓝，暴击，护甲，战斗力，动态计算(角色基本+装备)
            userRole = DynamicFunc(userRole, eqList);
            var result = new UserInfoModelResult(userRole, eqList,userBaseInfo);
            return result;
        }
        ////角色AP，血，蓝，暴击，护甲，战斗力，动态计算(角色基本+装备)
        private UserRoleModel DynamicFunc(UserRoleModel user, List<HeroEquipmentItem> eqList)
        {
            var result = user;
            result.ApValue = CallAttribute("ap", eqList) + user.ApValue;
            result.MagicPower = CallAttribute("lan", eqList) + user.MagicPower;
            result.HealthPoint = CallAttribute("xue", eqList) + user.HealthPoint;
            result.Armor = CallAttribute("hujia", eqList) + user.Armor;
            result.CriticalValue = CallAttribute("baoji", eqList) + user.CriticalValue;
            result.Power = CallAttribute("pow", eqList) + user.Power;
            return result;
        }
        private int CallAttribute(string type, List<HeroEquipmentItem> eqList)
        {
            var res = 0;
            switch (type)
            {
                case "ap":
                    for (var i = 0; i < eqList.Count; i++)
                    {
                        res += eqList[i].ApValue;
                    }
                    break;
                case "lan":
                    for (var i = 0; i < eqList.Count; i++)
                    {
                        res += eqList[i].InitMagicPower;
                    }
                    break;
                case "xue":

                    for (var i = 0; i < eqList.Count; i++)
                    {
                        res += eqList[i].InitHealthPoint;
                    }
                    break;
                case "hujia":
                    for (var i = 0; i < eqList.Count; i++)
                    {
                        res += eqList[i].InitArmor;
                    }
                    break;
                case "baoji":
                    for (var i = 0; i < eqList.Count; i++)
                    {
                        res += eqList[i].InitCriticalValue;
                    }
                    break;
                case "pow":
                    for (var i = 0; i < eqList.Count; i++)
                    {
                        res += eqList[i].Power;
                    }
                    break;
            }

            return res;
        }
        #endregion

        #region IWanMeiService 成员

        public void Dispose()
        {

        }

        #endregion
    }
}
